package cn.monkey.io.transport.core.server;

import cn.monkey.io.transport.core.Exchange;

import java.util.List;

public class DefaultFilterChain<EXCHANGE extends Exchange, PKG> implements FilterChain<EXCHANGE, PKG> {

    protected final List<Filter<EXCHANGE, PKG>> filters;

    protected final int index;

    private DefaultFilterChain(List<Filter<EXCHANGE, PKG>> filters, int index) {
        this.filters = filters;
        this.index = index;
    }


    public DefaultFilterChain(List<Filter<EXCHANGE, PKG>> filters) {
        this(filters, 0);
    }


    @Override
    public void doFilter(EXCHANGE exchange, PKG pkg) {
        if (this.filters == null) {
            return;
        }
        if (this.index >= this.filters.size()) {
            return;
        }
        this.filters.get(this.index).doFilter(exchange, pkg, new DefaultFilterChain<>(this.filters, index + 1));
    }
}
